﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace XWord.WPF.ApplicationFramework.Threads
{
    public class DelayTimer
    {
        DispatcherTimer gapValidateTimer;

        private ObservableCollection<object> _listenList { get; set; }

        public DelayTimer()
        {
            _listenList=new ObservableCollection<object>();
            _listenList.CollectionChanged += new NotifyCollectionChangedEventHandler(_listenList_CollectionChanged);
        }

        void _listenList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    ReStart();
                    break;
                case NotifyCollectionChangedAction.Move:
                    break;
                case NotifyCollectionChangedAction.Remove:
                    break;
                case NotifyCollectionChangedAction.Replace:
                    break;
                case NotifyCollectionChangedAction.Reset:
                    break;

            }
        }

        private void ReStart()
        {
            gapValidateTimer.Stop();
            gapValidateTimer.Start();
        }

        public void AddObj(object obj)
        {
            _listenList.Add(obj);
        }

        public void InitInvoke(double second, Action<object> action)
        {
            if (gapValidateTimer == null && second > 0)
            {
                gapValidateTimer = new DispatcherTimer();
                gapValidateTimer.Interval = TimeSpan.FromSeconds(second);
                gapValidateTimer.Tick += delegate
                {
                    if(_listenList.Count==0)
                        gapValidateTimer.Stop();
                    action(_listenList[_listenList.Count - 1]);
                    gapValidateTimer.Stop();
                    _listenList.Clear();
                };
            }
        }
    }
}
